<?php

/**
 * descript:电子邮箱
 * PHPMailer\PHPMailer
 * User: blue
 * Date: 2018/9/10 15:58
 */

namespace rabbit\composer\email;

use PHPMailer\PHPMailer\PHPMailer;
use think\facade\Config;

class Email{
    private $phpMailer;
    public function __construct()
    {
        if(!$this->phpMailer instanceof PHPMailer){
            $this->phpMailer=new PHPMailer();
        }
    }

    /**
     * @param $toMail 接收邮箱地址,为数组时为群发
     * @param $content 邮件内容
     * @param $title 邮件标题
     * @return bool 发送结果
     * @throws \PHPMailer\PHPMailer\Exception
     */
    public function sendEmail($toMail,$content,$title){
        try {
            //Server settings
            $this->phpMailer->SMTPDebug = 2;                                 // Enable verbose debug output
            $this->phpMailer->CharSet="utf-8";
            $this->phpMailer->isSMTP();                                      // Set mailer to use SMTP
            $this->phpMailer->Host = Config::get('email.host');  // Specify main and backup SMTP servers
            $this->phpMailer->SMTPAuth = true;         // Enable SMTP authentication
            $this->phpMailer->Username =Config::get('email.username');                 // SMTP username
            $this->phpMailer->Password = Config::get('email.password');                           // SMTP password
            $this->phpMailer->SMTPSecure = 'ssl';      // Enable TLS encryption, `ssl` also accepted
            $this->phpMailer->Port = Config::get('email.port');                                // 465,994

            $this->phpMailer->setFrom(Config::get('email.username'), Config::get('email.send_email_sign'));
            if(is_array($toMail)&&!empty($toMail)){
                foreach ($toMail as $v){
                    $this->phpMailer->addAddress($v);
                }
            }else{
                $this->phpMailer->addAddress($toMail);
            }

            //Content
            $this->phpMailer->isHTML(true);
            $this->phpMailer->Subject = $title;
            $this->phpMailer->Body    = $content;
            $res=$this->phpMailer->send();
            echo 'Message has been sent';
            return $res;
        } catch (Exception $e) {
            echo 'Message could not be sent. Mailer Error: ', $this->phpMailer->ErrorInfo;
        }
    }

}